package com.iexbuy.ihg.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.iexbuy.ihg.App;
import com.iexbuy.ihg.R;
import com.iexbuy.ihg.adapter.ViewPageAdapter;
import com.iexbuy.ihg.common.CommUtil;
import com.iexbuy.ihg.common.ExtraKeyConstant;
import com.iexbuy.ihg.entity.UserObject;
import com.iexbuy.ihg.entity.UserObjectResponse;
import com.iexbuy.ihg.net.ServiceHelper;
import com.iexbuy.ihg.ui.activity.MainTabActivity;
import com.iexbuy.ihg.ui.activity.SingleFragmentActivity;
import com.iexbuy.ihg.ui.activity.StartActivity;
import com.iexbuy.ihg.utils.JsonUtils;
import com.iexbuy.ihg.utils.StringUtil;
import com.iexbuy.ihg.utils.ToastUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

public class LoginFragment extends BaseFragment {
	
	/** log tag. */
    private WebView mWebView;
    /** redirect uri 值为"oob" */
    private static final String REDIRECT = "oob";
    /** 开发中心 */
    static final String DEV_CENTER = "https://openapi.baidu.com/";

	@ViewInject(R.id.userName)
	private EditText userName;
	@ViewInject(R.id.password)
	private EditText password;
	@ViewInject(R.id.mobileNo)
	private EditText mobileNo;
	@ViewInject(R.id.validateCode)
	private EditText validateCode;
	@ViewInject(R.id.regPassword)
	private EditText regPassword;
	@ViewInject(R.id.jumpRegisterBtn)
	private TextView jumpRegisterBtn;
	@ViewInject(R.id.jumpLoginBtn)
	private TextView jumpLoginBtn;
	@ViewInject(R.id.jumpForgetPasswordBtn)
	private TextView jumpForgetPasswordBtn;
	@ViewInject(R.id.getValidateCodeBtn)
	private TextView getValidateCodeBtn;

	//分页
	@ViewInject(R.id.viewpager)
	private ViewPager mViewPager;
	private ViewPageAdapter mPageAdapter;
	private List<View> mListViews;
	private int mViewCurrentPageIndex;

	private View loginView;
	private View registerValidationView;

	private static boolean isLoginForbusiness;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected View _onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_login, container, false);
		ViewUtils.inject(this, rootView);
		initView(rootView);
		return rootView;
	}

	private void initView(View view) {
		mBaseActivity.setTitle(mBaseActivity.getResources().getString(R.string.title_login));
		mBaseActivity.setTitleLayoutVisibility(false);
		mBaseActivity.setLeftButtonVisibility(View.GONE);

		initViewPage();

		ViewUtils.inject(this, loginView);
		ViewUtils.inject(this, registerValidationView);

		if (StringUtil.isNotEmpty(App.sPreferences.getUserName())) {
//			rememberme.setChecked(true);
			userName.setText(App.sPreferences.getUserName());
			password.setText(App.sPreferences.getPsw());
//			
//			if (App.sPreferences.isLoginIn()) {
//				onLoginClick(null);//自动登录
//			}
//			
//			mBaseActivity.startActivity(new Intent(mBaseActivity, MainTabActivity.class));
//			mBaseActivity.finish();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		mBaseActivity.setHomeActivity(true);
	}

	@OnClick(R.id.loginBtn)
	public void onLoginClick(View arg0) {
		//较验
		if (userName.getText() == null || TextUtils.isEmpty(userName.getText().toString())) {
			ToastUtils.toast(mBaseActivity, "请输入用户名。");
			return;
		}
		if (password.getText() == null || TextUtils.isEmpty(password.getText().toString())) {
			ToastUtils.toast(mBaseActivity, "请输入密码。");
			return;
		}
		
		//登录
//		String passwrodMD5 = MD5.getMD5(password.getText().toString());
//		startFragment(mBaseActivity, R.id.fragmentContainer, new HomeFragment());
		login(userName.getText().toString(), password.getText().toString());
		
	}

	@OnClick(R.id.jumpRegisterBtn)
	public void onJumpRegisterBtn(View view) {
		jumpRegisterBtn.setVisibility(View.GONE);
		jumpLoginBtn.setVisibility(View.VISIBLE);
		mViewPager.setCurrentItem(1);
	}

	@OnClick(R.id.jumpLoginBtn)
	public void onJumpLoginBtn(View view) {
		jumpRegisterBtn.setVisibility(View.VISIBLE);
		jumpLoginBtn.setVisibility(View.GONE);
		mViewPager.setCurrentItem(0);
	}

	@OnClick(R.id.jumpForgetPasswordBtn)
	public void onJumpForgetPasswordBtn(View view) {
		Intent intent = new Intent(mBaseActivity, SingleFragmentActivity.class);
		intent.putExtra(ExtraKeyConstant.KEY_FRAGMENT, ForgetPsswrodFragment.class);
		intent.putExtra(ExtraKeyConstant.KEY_FINISH_ACTIVITY, true);
		startActivity(intent);
	}

	private void initViewPage() {
		mListViews = new ArrayList<View>();
		LayoutInflater mLayoutInflater = mBaseActivity.getLayoutInflater();

		loginView = mLayoutInflater.inflate(R.layout.fragment_login_input, null);
		registerValidationView = mLayoutInflater.inflate(R.layout.fragment_register_validate, null);

		mListViews.add(loginView);
		mListViews.add(registerValidationView);

		mPageAdapter = new ViewPageAdapter(mListViews);
		mViewPager.setAdapter(mPageAdapter);
		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}

			@Override
			public void onPageScrolled(int index, float arg1, int arg2) {
				mViewCurrentPageIndex = index;
				if (index == 0) {
					jumpForgetPasswordBtn.setVisibility(View.VISIBLE);
				} else if (index == 1) {
					jumpForgetPasswordBtn.setVisibility(View.GONE);
				}
			}

			@Override
			public void onPageSelected(int index) {
			}
		});
		//禁止滑动
		mViewPager.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent motionEvent) {
				return true;
			}
		});
		mViewPager.setCurrentItem(0);
	}
	
	private void login(final String username, final String passwordMd5) {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("username", username);
		paramMap.put("pwd", passwordMd5);

		ServiceHelper.send(mBaseActivity, ServiceHelper.LOGIN, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("登录中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();
						ToastUtils.toast(mBaseActivity, "登录成功。");
						String responseString = responseInfo.result;
						Log.i("", responseString);
						UserObjectResponse userInfo = JsonUtils.parseJsonStrToObject(responseString, UserObjectResponse.class);

						if (userInfo.getResultCode() == 0) {

							App.sPreferences.setUserName(username);
							App.sPreferences.setName(userInfo.getBody().getName());
							App.sPreferences.setPsw(passwordMd5);
							App.sPreferences.setUserId(userInfo.getBody().getId());
							App.sPreferences.setLoginIn(true);


							if (!LoginFragment.isLoginForbusiness) {
								startActivity(new Intent(mBaseActivity, MainTabActivity.class));
							} else {
								LoginFragment.isLoginForbusiness = false;
							}

							mBaseActivity.finish();
							if (StartActivity.getInstance() != null) {
								StartActivity.getInstance().finish();
							}
						} else {
							ToastUtils.toast(mBaseActivity, userInfo.getResultMessage());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						if (msg.contains("apache.http.conn")) {
							CommUtil.showAlert(mBaseActivity, "登录失败", "连接不上服务器", null);
						} else {
							CommUtil.showAlert(mBaseActivity, "登录失败", "用户名或密码不对", null);
						}

					}
				});
	}


	@OnClick(R.id.getValidateCodeBtn)
	public void onGetValidateCode(View view) {
		String mobile = mobileNo.getText().toString();
		if (TextUtils.isEmpty(mobile)) {
			ToastUtils.toast(mBaseActivity, "请输入手机号码。");
		} else {
			HashMap<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("mobileNo", mobile);

			ServiceHelper.send(mBaseActivity, ServiceHelper.GET_VERIFYCODE, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("请求中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();
						ToastUtils.toast(mBaseActivity, "验证码已发送，请留意手机短信。");
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						if (msg.contains("apache.http.conn")) {
							CommUtil.showAlert(mBaseActivity, "登录失败", "连接不上服务器", null);
						} else {
							CommUtil.showAlert(mBaseActivity, "登录失败", msg, null);
						}

					}
				});
		}
	}

	@OnClick(R.id.checkValidaCodeBtn)
	public void onGheckValidaCodeBtn(View view) {
		String valCode = validateCode.getText().toString();
		final String mobile = mobileNo.getText().toString();
		final String password = regPassword.getText().toString();
		if (TextUtils.isEmpty(mobile)) {
			ToastUtils.toast(mBaseActivity, "请输入手机号码。");
			return;
		}
		if (TextUtils.isEmpty(valCode)) {
			ToastUtils.toast(mBaseActivity, "请输入验证码。");
			return;
		}
		if (TextUtils.isEmpty(password)) {
			ToastUtils.toast(mBaseActivity, "请输入密码。");
			return;
		}

		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("mobileNo", mobile);
		paramMap.put("verifyCode", valCode);

		ServiceHelper.send(mBaseActivity, ServiceHelper.CHECK_VERIFY_CODE, paramMap,
			new RequestCallBack<String>() {
				@Override
				public void onStart() {
					mBaseActivity.showDialog("请求中...");
				}

				@Override
				public void onCancelled() {
					mBaseActivity.closeDialog();
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					mBaseActivity.closeDialog();

					sendPassword(mobile, password);
				}

				@Override
				public void onFailure(HttpException error, String msg) {
					mBaseActivity.closeDialog();
					if (msg.contains("apache.http.conn")) {
						CommUtil.showAlert(mBaseActivity, "登录失败", "连接不上服务器", null);
					} else {
						CommUtil.showAlert(mBaseActivity, "登录失败", msg, null);
					}

				}
			});
	}

	private void sendPassword(final String mobile, final String password) {
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("mobileNo", mobile);
		paramMap.put("password", password);

		ServiceHelper.send(mBaseActivity, ServiceHelper.REGISTER_WITH_PASSWORD, paramMap,
				new RequestCallBack<String>() {
					@Override
					public void onStart() {
						mBaseActivity.showDialog("请求中...");
					}

					@Override
					public void onCancelled() {
						mBaseActivity.closeDialog();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						mBaseActivity.closeDialog();

						ToastUtils.toast(mBaseActivity, "恭喜！注册成功！");

						login(mobile, password);
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						mBaseActivity.closeDialog();
						if (msg.contains("apache.http.conn")) {
							CommUtil.showAlert(mBaseActivity, "登录失败", "连接不上服务器", null);
						} else {
							CommUtil.showAlert(mBaseActivity, "登录失败", msg, null);
						}

					}
				});

	}

	public static void setIsLoginForbusiness(boolean isLoginForbusiness) {
		LoginFragment.isLoginForbusiness = isLoginForbusiness;
	}
}
